package com.zxtyshangjia.zxtyjms.business.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.zxtyshangjia.zxtyjms.R;
import com.zxtyshangjia.zxtyjms.base.BaseBean;
import com.zxtyshangjia.zxtyjms.login.activity.LoginActivity;
import com.zxtyshangjia.zxtyjms.order.bean.Areabean;
import com.zxtyshangjia.zxtyjms.order.bean.ClassBean;
import com.zxtyshangjia.zxtyjms.order.bean.ClassifyBean;
import com.zxtyshangjia.zxtyjms.utils.Api;
import com.zxtyshangjia.zxtyjms.utils.SpUtils;
import com.zxtyshangjia.zxtyjms.utils.ToastUtil;
import com.zxtyshangjia.zxtyjms.utils.WheelViewPopwindow;
import com.zxtyshangjia.zxtyjms.utils.network.HttpUtil;
import com.zxtyshangjia.zxtyjms.utils.network.PostCallBack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 18222 on 2017/11/16.
 * 添加商家页
 */

public class AddShangjiaActivity extends TakePhotoActivity {

    private static final int TAKEADDRESS = 10010;

    /**
     * 详细地址 点击事件
     */
    private LinearLayout mDetailAddressLL;

    /**
     *  详细地址 显示
     */
    private TextView mDetailAddressTV;
    private String mAddress = "";


    /**
     * 上传图片
     */
    com.jph.takephoto.app.TakePhoto takePhoto;

    private View popview;

    private PopupWindow popwindow;

    /**
     * 手机号
     */
    private EditText mCallphoneNumET;
    private String mCallphoneNum;

    /**
     * 密码
     */
    private EditText mPasswordET;
    private String mPassword;
    /**
     * 确认密码
     */
    private EditText mConfirmPwordET;
    private String mConfirmPword;
    /**
     * 店名
     */
    private EditText mShopNameET;
    private String mShopName;
    /**
     * 分类
     */
    private TextView mShopSortTV;
    private String mShopSort;

    /**
     * 资质 上传的照片
     */
    private ImageView picIV1;
    private ImageView picIV2;
    private ImageView picIV3;

    /**
     * 记录当前有几张资质图
     */
    private int picNum;

    /**
     * 三张图片的存储路径
     */
    private String pic1Path;
    private String pic2Path;
    private String pic3Path;

    /**
     * 三张图片的文件
     */
    private File pic1ImageFile;
    private File pic2ImageFile;
    private File pic3ImageFile;


    /**
     * 注册
     */
    private TextView mRegistSubmitTV;

    /**
     * 当前加盟商 地理位置显示
     */
    private TextView mCurrentAddressTV;

    /**
     * 选择区
     * 如果加盟商为市级加盟商  则加盟商可以选择区  如果是区级/县级 则不能选择区级地址
     * 有点击事件
     */
    private TextView mChooseAreaTV;

    /**
     *  分类数组
     */

    private ClassBean cBean;

    private ArrayList<ClassifyBean> classList = new ArrayList<>();

    private List<String> className = new ArrayList<>();

    /**
     * 地区数组
     */

    private ArrayList<Areabean> areaList = new ArrayList<>();
    private List<String> areaName = new ArrayList<>();

    private String mAreaName;


    private String e_id;

    private Object object;

    /**
     * 添加商家要传给后台的参数
     * class_id 分类id
     * province 	省级id
     * city 	市级id
     * area 	县级id
     lnt 	经度
     lat 	纬度
     */

    private String class_id = "";
    private String province;
    private String city;
    private String area;
    private String lnt;
    private String lat;

    //注册回调
    private PostCallBack registerBack = new PostCallBack() {
        @Override
        public void onSuccess(Object data) {
            if(data != null && data instanceof BaseBean){
                BaseBean baseBean = (BaseBean) data;
                if(baseBean.flag.equals("success")){
                    ToastUtil.showToast("注册成功，审核通过即可登录");
                    Intent intent= new Intent(AddShangjiaActivity.this,LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
                else {
                    ToastUtil.showToast(baseBean.message);
                }
            }

        }

        @Override
        public void onError(int code, String msg) {
            ToastUtil.showToast(msg);

        }
    };

    /**
     * 点击侦听
     */
    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(view.getId() == mShopSortTV.getId()){
                //分类

                new WheelViewPopwindow(AddShangjiaActivity.this, className , mShopSortTV, new WheelViewPopwindow.OnSuccessClick() {
                    @Override
                    public void onSuccessClick(int position, String content) {

                        Log.e("position & content ==",position + "  " + content);

                        class_id = classList.get(position).class_id;
                        Log.e("classList i name =====",classList.get(position).name);
                        Log.e("class_id =====",class_id);

                    }
                }).showPop();

            }else if(view.getId() == mRegistSubmitTV.getId()){
                //商家注册
                mCallphoneNum = mCallphoneNumET.getText().toString();
                mPassword = mPasswordET.getText().toString();
                mConfirmPword = mConfirmPwordET.getText().toString();
                mShopName = mShopNameET.getText().toString();    //店名 商家的名称

                if(mCallphoneNum.equals("")){
                    ToastUtil.showToast("手机号不能为空");
                }else if(!isMobileNO(mCallphoneNum)){
                    ToastUtil.showToast("请填写正确的手机号码");
                }else if(mPassword.equals("")){
                    ToastUtil.showToast("密码不能为空");
                }else if(mConfirmPword.equals("")){
                    ToastUtil.showToast("确认密码不能为空");
                }else if(!mPassword.equals(mConfirmPword)){
                    ToastUtil.showToast("您两次输入的密码不一致");
                }else if(mShopName.equals("")){
                    ToastUtil.showToast("商家名不能为空");
                }else if(class_id.equals("")){
                    ToastUtil.showToast("请选择商家分类");
                }else if(mAddress.equals("")){
                    ToastUtil.showToast("请完善商家地址");
                }else if(pic1ImageFile == null){
                    ToastUtil.showToast("请至少上传一张商家资质图");
                }else {

                    Map<String,String> map = new HashMap<>();
                    map.put("account",mCallphoneNum);
                    map.put("name",mShopName);
                    map.put("password",mPassword);
                    map.put("re_password",mConfirmPword);
                    map.put("class_id",class_id);
                    map.put("app_type","1");
                    map.put("province",province);
                    map.put("city",city);
                    map.put("area",area);
                    map.put("address",mAddress);
                    map.put("lnt",lnt);
                    map.put("lat",lat);


                    ArrayList<File> list = new ArrayList<>();
                    list.add(pic1ImageFile);
                    if( pic2ImageFile!= null){
                        list.add(pic2ImageFile);
                    }
                    if( pic3ImageFile!= null){
                        list.add(pic3ImageFile);
                    }

                    new HttpUtil(Api.CASH_ADDSHOP,map,"Shop",list,BaseBean.class,registerBack).postExecute();
                }

            }else if(view.getId() == picIV1.getId()){
                //点击第一张图  记录当前位置  弹出底部选项框
                picNum = 1;
                showTakePhoto();


            }else if(view.getId() == picIV2.getId()){
                //点击第二张图  记录当前位置  弹出底部选项框

                picNum = 2;
                showTakePhoto();


            }else if(view.getId() == picIV3.getId()){
                //点击第三张图  记录当前位置  弹出底部选项框

                picNum = 3;
                showTakePhoto();


            }else if(view.getId() == mDetailAddressLL.getId()){
                //详细地址点击事件

                mShopSort = mShopSortTV.getText().toString();   //分类
                if( area.equals("") || mShopSort.equals("")){
                    ToastUtil.showToast("请先选择地区及分类");
                }else {
                    Intent intent = new Intent(AddShangjiaActivity.this,GaodeSearchForActivity.class);
                    intent.putExtra("city",mAreaName);
                    intent.putExtra("deepType",mShopSort);
                    intent.putExtra("type",-999);
                    startActivityForResult(intent,TAKEADDRESS);
                }




            }else if(view.getId() == mChooseAreaTV.getId()){
                //选择地区

                new WheelViewPopwindow(AddShangjiaActivity.this, areaName , mChooseAreaTV, new WheelViewPopwindow.OnSuccessClick() {
                    @Override
                    public void onSuccessClick(int position, String content) {

                        Log.e("position & content ==",position + "  " + content);

                        area = areaList.get(position).area_id;
                        mAreaName = areaList.get(position).area_name;

                        Log.e("classList i name =====",classList.get(position).name);
                        Log.e("class_id =====",class_id);

                    }
                }).showPop();


            }
        }
    };

    //跳转高德地图得到的结果回调  得到经纬度 把并把地址显示到控件上
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == TAKEADDRESS){
            if(data != null){
                mAddress = data.getStringExtra("mAddress");
                lat = data.getStringExtra("latitude");
                lnt = data.getStringExtra("longititude");
                mDetailAddressTV.setText(mAddress);
            }
        }
    }



    //弹出底部选项框 处理拍照等
    private void showTakePhoto() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        popview = layoutInflater.inflate(R.layout.pop_picture_select, null);
        RelativeLayout btnBendi = (RelativeLayout) popview.findViewById(R.id.btn_bendi);
        RelativeLayout btnCancel = (RelativeLayout) popview.findViewById(R.id.btn_cancel);
        RelativeLayout btnCapture = (RelativeLayout) popview.findViewById(R.id.btn_paizhao);
        popwindow = new PopupWindow(popview, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popwindow.setBackgroundDrawable(new ColorDrawable(0x80000000));
        popwindow.setAnimationStyle(R.style.AnimBottom);
        popwindow.setTouchable(true);
        popwindow.setOutsideTouchable(true);
        popwindow.setFocusable(true);
        //虚拟按钮遮挡pop 所以要添加这条
        popwindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (!popwindow.isShowing()) {
            //虚拟按钮遮挡pop 使用activity.getWindow().getDecorView()
            popwindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        }
        //取消
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popwindow.isShowing()) {
                    popwindow.dismiss();
                }
            }
        });

        //本地相册
        btnBendi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTakePhoto();
                takePhoto.onPickMultiple(1);
                if (popwindow.isShowing()) {
                    popwindow.dismiss();
                }
            }
        });

        //拍照
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTakePhoto();
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                Uri imageUri = Uri.fromFile(file);
                takePhoto.onPickFromCapture(imageUri);
                if (popwindow.isShowing()) {
                    popwindow.dismiss();
                }
            }
        });

    }


    /**
     * 设置TakePhoto  照片的相关设置
     */
    private void setTakePhoto() {
        takePhoto = null;
        if (takePhoto == null) {
            takePhoto = getTakePhoto();
            TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
            builder.setCorrectImage(true);
            takePhoto.setTakePhotoOptions(builder.create());  //是否纠正照片旋转
            CompressConfig config = new CompressConfig.Builder()
                    .setMaxSize(700000) //压缩最大值
                    .setMaxPixel(800)
                    .enableReserveRaw(false) //压缩后是否保存原图
                    .create();
            takePhoto.onEnableCompress(config, false);//压缩图像
        }
    }


    //照片上传成功的回调
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Log.e("**********************","*****");

        ArrayList<TImage> images = result.getImages();
        if (picNum == 1) {
            //图一
            if (images.get(0).getCompressPath() == null) {
                pic1Path = images.get(0).getOriginalPath();
            } else {
                pic1Path = images.get(0).getCompressPath();
            }
            Glide.with(this)
                    .load(pic1Path)
                    .centerCrop()
                    .into(picIV1);
            picIV2.setVisibility(View.VISIBLE);
            pic1ImageFile = new File(pic1Path);
        } else if (picNum == 2) {
            //图二
            if (images.get(0).getCompressPath() == null) {
                pic2Path = images.get(0).getOriginalPath();
            } else {
                pic2Path = images.get(0).getCompressPath();
            }
            Glide.with(this)
                    .load(pic2Path)
                    .centerCrop()
                    .into(picIV2);
            picIV3.setVisibility(View.VISIBLE);
            pic2ImageFile = new File(pic2Path);
        } else if (picNum == 3) {
            //图三
            if (images.get(0).getCompressPath() == null) {
                pic3Path = images.get(0).getOriginalPath();
            } else {
                pic3Path = images.get(0).getCompressPath();
            }
            Glide.with(this)
                    .load(pic3Path)
                    .centerCrop()
                    .into(picIV3);
            pic3ImageFile = new File(pic3Path);
        }
    }

    //照片上传失败的回调
    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("**********************","&&&&&");
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    //操作取消 比如按下返回键 回调
    @Override
    public void takeCancel() {
        super.takeCancel();
        Log.e("**********************","+++++");
        Toast.makeText(this, "操作取消", Toast.LENGTH_SHORT).show();
    }



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_shangjia);
        e_id = SpUtils.getInstance(AddShangjiaActivity.this).getString("e_id","");
        bindView();
        initData();
        bindListener();

    }

    private void initData() {
        //初始化 分类和地区

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(Api.CASH_AGENT + "?e_id=" + e_id)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //解析返回的结果
                try {
                    Log.e("=========response", String.valueOf(response));
                    Class responseClass = ClassBean.class;
                    final String res = response.body().string();
                    Log.e("=========res", res);
                    object = new Gson().fromJson(res, responseClass);
                } catch (Exception e) {
                    Log.e("=======", "error");
                    return;
                }
                if (object != null && object instanceof ClassBean) {
                    cBean = (ClassBean) object;
                    if (cBean.flag.equals("success")) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                mCurrentAddressTV.setText(cBean.data.province.area_name + "/" + cBean.data.city.area_name);
                                province = cBean.data.province.area_id;
                                city = cBean.data.city.area_id;

                                //分类
                                classList.addAll(cBean.data.classify);

                                if(classList.size() > 0){

                                    for(int i = 0 ; i < classList.size();i++){
                                        className.add(classList.get(i).name);
                                    }
                                    Log.e("classList =======",classList.toString());
                                }

                                areaList.addAll(cBean.data.area);
                                if(areaList.size() == 1){

                                    mCurrentAddressTV.setText(cBean.data.province.area_name + "/"
                                            + cBean.data.city.area_name + "/" + areaList.get(0).area_name);

                                    mChooseAreaTV.setVisibility(View.GONE);

                                    area = areaList.get(0).area_id;
                                    mAreaName = areaList.get(0).area_name;

                                }else {

                                    for(int i = 0; i < areaList.size(); i++ ){
                                        areaName.add(areaList.get(i).area_name);
                                    }
                                    Log.e("areaList =======",areaList.toString());

                                }
                            }
                        });

                    }
                }
            }
        });
    }

    private void bindListener() {
        //初始化点击事件

        mShopSortTV.setOnClickListener(mClickListener);
        mRegistSubmitTV.setOnClickListener(mClickListener);
        picIV1.setOnClickListener(mClickListener);
        picIV2.setOnClickListener(mClickListener);
        picIV3.setOnClickListener(mClickListener);
        mDetailAddressLL.setOnClickListener(mClickListener);
        mChooseAreaTV.setOnClickListener(mClickListener);

    }

    private void bindView() {

        mCallphoneNumET = (EditText) findViewById(R.id.callphone_num_et);
        mPasswordET = (EditText) findViewById(R.id.password_et);
        mConfirmPwordET = (EditText) findViewById(R.id.confirm_pd_et);
        mShopNameET = (EditText) findViewById(R.id.shop_name_et);
        mShopSortTV = (TextView) findViewById(R.id.sort_tv);
        mRegistSubmitTV = (TextView) findViewById(R.id.regist_submit_tv);
        picIV1 = (ImageView) findViewById(R.id.picture_iv1);
        picIV2 = (ImageView) findViewById(R.id.picture_iv2);
        picIV3 = (ImageView) findViewById(R.id.picture_iv3);
        mDetailAddressLL = (LinearLayout) findViewById(R.id.address_detail_ll);
        mDetailAddressTV = (TextView) findViewById(R.id.address_detail_tv);
        mCurrentAddressTV = (TextView) findViewById(R.id.current_address_tv);
        mChooseAreaTV = (TextView) findViewById(R.id.address_area);


    }

    /**
     *  
     *  * 验证手机格式 
     *  
     */
    public static boolean isMobileNO(String mobiles) {
   /* 
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 
    联通：130、131、132、152、155、156、185、186 
    电信：133、153、180、189、（1349卫通） 
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9 
    */
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。  
        String telRegex = "[1][358]\\d{9}";
        return mobiles.matches(telRegex);
    }
}
